package firehwak.thoth.client.database;

import java.util.ArrayList;
import java.util.List;

import firehwak.thoth.client.data.Data;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class LocalDatabase {
	private SQLiteDatabase database;

	private DatabaseHelper databaseHelper;

	public LocalDatabase(Context c) {
		databaseHelper = new DatabaseHelper(c, "thoth_client", null, 1);
	}

	public void close() {
		database.close();
	}

	public void open() throws SQLiteException {
		try {
			database = databaseHelper.getWritableDatabase();
		} catch (SQLiteException ex) {
			database = databaseHelper.getReadableDatabase();
		}
	}

	public long insertData(double latitude, double longitude, int signalStrength) {
		ContentValues values = new ContentValues();
		values.put("latitude", latitude);
		values.put("longitude", longitude);
		values.put("signalStrength", signalStrength);
		values.put("timestamp", System.currentTimeMillis());
		long ret = database.insert("localStorage", null, values);

		return ret;
	}

	public List<Data> getDataList() {
		Cursor c = database.query("localStorage", null, null, null, null, null, null);

		List<Data> list = new ArrayList<Data>();

		if (c.moveToFirst()) do {
			Data data = new Data();
			data.latitude = (float) c.getDouble(c.getColumnIndex("latitude"));
			data.longitude = (float) c.getDouble(c.getColumnIndex("longitude"));
			data.strength = c.getFloat(c.getColumnIndex("signalStrength"));
			data.timestamp = c.getLong(c.getColumnIndex("timestamp"));
			
			long currentTime = System.currentTimeMillis();
			if (currentTime - data.timestamp > 6 * 60 * 60 * 1000) {
				continue;
			}
			
			list.add(data);
		} while (c.moveToNext());

		c.close();

		return list;

	}

	private class DatabaseHelper extends SQLiteOpenHelper {
		private static final String CREATE_TABLE_QUERY = "CREATE TABLE localStorage (latitude double not null, longitude double not null, signalStrength int not null, timestamp int not null)";

		public DatabaseHelper(Context context, String name, CursorFactory factory, int version) {
			super(context, name, factory, version);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			try {
				db.execSQL(CREATE_TABLE_QUERY);
			} catch (SQLiteException ex) {
				Log.v("thoth", ex.getLocalizedMessage());
			}
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("drop table if exists localStorage");
			onCreate(db);
		}

	}
}
